﻿using Dapper;
using Logistics.Model;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace Logistics.Track
{
    public class CargoownerTrackAppService : ICargoownerTrackAppService
    {
        private readonly IRepository<Contracttracking, int> _cargoownerRepository;
        private readonly ICargoownerTrackRepository _cargoownertrack;
        public CargoownerTrackAppService(IRepository<Contracttracking, int> cargoownerRepository, ICargoownerTrackRepository cargoownertrack)
        {
            _cargoownerRepository = cargoownerRepository;
            _cargoownertrack = cargoownertrack;
        }
        public async Task<PagedResultDto<CargoownerTrackDto>> GetDapperCargoownerTracks(CargoownerTrackSearchDto csd)
        {
            string sql = "select a.*,b.NumberId,b.ContractTitle,b.OwnerUnit,b.PersoninCharge,b.Line,b.Freightrate,b.CharterConditions,b.CreateTimedate,b.SigningDate,b.CharterAmount,b.`Handler`,c.`Name` Fname,d.`Name` Oname,e.`Name` Lname from Contracttracking a right join cargoowner b on a.ContractId=b.Id join field c on b.OwnerUnit=c.Id join `owner` d on b.PersoninCharge=d.Id join line e on b.Line=e.Id where 1=1";
            string sql1 = sql + " order by b.Id limit " + csd.MaxResultCount + "," + csd.SkipCount;
            using (IDbConnection conn = new MySqlConnection("Server=10.31.64.9;Port=3306;Database=Logistics;Uid=si;Pwd=111111;"))
            {
                conn.Open();
                var count = (List<CargoownerTrackDto>)await conn.QueryAsync<CargoownerTrackDto>(sql1);
                int totalCount = count.Count();
                var list = (List<CargoownerTrackDto>)await conn.QueryAsync<CargoownerTrackDto>(sql);
                return new PagedResultDto<CargoownerTrackDto>(
                  totalCount,
                  list.ToList()
                );
            }
        }

        public async Task<int> UpdateCargoownerTrack(int Id, string Condition)
        {
            var carrytract = _cargoownerRepository.GetAsync(Id).Result;
            carrytract.Condition = Condition;
            int result = await _cargoownertrack.Update(carrytract);
            return result;
        }
    }
}
